<?php

namespace App\Controller\Wap;

use App\Entity\ShopGoods;
use App\Entity\UserLikesProduct;
use App\Model\MoneyExModel;
use App\Model\MoneyLogModel;
use App\Model\MoneyModel;
use App\Model\ShopGoodsModel;
use App\Model\UserDiyLevelupLimitModel;
use App\Model\UserDiyLevelUpModel;
use App\Model\UserLikesProductModel;
use App\Base\BaseConfig;
use App\Base\BaseController4User;
use BaseExt\QRcode;
use App\Model\LazyCommon\CCM;
use App\Model\LazyCommon\PlatConfigModel;
use App\Model\LazyCommon\UserModel;
use App\Model\LazyCommon\UserInviteExModel;
use App\Model\LazyCommon\WechatModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;


/**
 * @route("/wap")
 */
class ShareController extends BaseController4User
{

    /**
     * @route("/share/code",name="UserAppShareCode")
     */
    public function UserAppShareCode()
    {
        $uid = $this->needToBeUser();
        $UserInviteExModel= new UserInviteExModel($this->getDoctrine());
        $UserInvite = $UserInviteExModel->getUser($uid);
        $code = $UserInvite->getCode();
        $qrCode = BaseConfig::__BASE_URL__.$this->generateUrl("UserAppShareReg",array("code"=>$code));
//        $qrImg = BaseConfig::__BASE_URL__.$this->generateUrl("Qr")."?code=".$qrCode;

        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 12;//生成图片大小
//        生成二维码图片
        $tmpFile = "./tmp/".uniqid($uid).rand(100000,99999999).".png";
        $img = QRcode::png($qrCode, $tmpFile, $errorCorrectionLevel, $matrixPointSize, 2);
//        var_dump($img);
//        $img = 'uploads/01.png';
        $base64_img = $this->base64EncodeImage($tmpFile);

        $this->data["qrImg"] = $base64_img;


        //获取用户信息
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);
        $userInfo = $UserModel->getBaseInfo($user);
        $this->data["user"] = $userInfo;

        return $this->render("App/Wap/share_code.php.twig",$this->data);
    }

private function base64EncodeImage ($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    /**
     * @route("/share/rank/money",name="UserAppShareRankMoney")
     */
    public function UserAppShareRankMoney()
    {
        $Model = new MoneyExModel($this->getDoctrine());

        $this->getMoneyRankList(1);
        $this->getMoneyRankList(2);
        $this->getMoneyRankList(3);

        return $this->render("App/Wap/share_rank_money.php.twig",$this->data);
    }

    private function getMoneyRankList($type)
    {
        switch ($type) {
            case 1://每天
                $keyWord = "day";
                $start = $this->getDayStart();
                $end = $this->getDayEnd();
                break;
            case 2://每周
                $keyWord = "week";
                $start = $this->getWeekStart();
                $end = $this->getWeekEnd();
                break;
            case 3://每月
                $keyWord = "month";
                $start = $this->getMonthStart();
                $end = $this->getMonthEnd();
                break;
            default:
                $keyWord = "day";
                $start = $this->getDayStart();
                $end = $this->getDayEnd();
        }

        $Model = new MoneyExModel($this->getDoctrine());

        $list = $Model->getMoneyRankList($start,$end);


        $this->data[$keyWord]["all"] = $list;

//        var_dump($list);

        $emptyUser = array(
            "nickName" => "虚位以待",
            "headPic" => BaseConfig::__USER_PIC_DEFAULT__,
            "money" => 0,
        );
        if (count($list) < 10) {
            for ( $i = count($list); $i < 10 ; $i++ ) {
                $list[$i] = $emptyUser;
            }
        }
        foreach ($list as $key => &$one) {
            $one["index"] = $key + 1;
            if (!$one["nickName"]) {
                $one["nickName"] = "萱氧会员_".$one["uid"];
//                $one["headPic"] = BaseConfig::__USER_PIC_DEFAULT__;
                $one["money"] = floor($one["money"] * 100)/100;
            }
            $one["money"] .=" ";
        }
        $this->data[$keyWord]["one"] = $list[0];
        $this->data[$keyWord]["two"] = $list[1];
        $this->data[$keyWord]["three"] = $list[2];
        $this->data[$keyWord]["list"] = array_slice($list,3);
    }

    /**
     * @route("/share/rank/donate",name="UserAppShareRankDonate")
     */
    public function UserAppShareRankDonate()
    {
        $this->getDonateList(1);
        $this->getDonateList(2);
        $this->getDonateList(3);
//        var_dump($this->data);
        return $this->render("App/Wap/share_rank_love.php.twig",$this->data);
    }

    private function getDonateList($type)
    {
        switch ($type) {
            case 1://每天
                $keyWord = "day";
                $start = $this->getDayStart();
                $end = $this->getDayEnd();
                break;
            case 2://每周
                $keyWord = "week";
                $start = $this->getWeekStart();
                $end = $this->getWeekEnd();
                break;
            case 3://每月
                $keyWord = "month";
                $start = $this->getMonthStart();
                $end = $this->getMonthEnd();
                break;
            default:
                $keyWord = "day";
                $start = $this->getDayStart();
                $end = $this->getDayEnd();
        }

        $Model = new MoneyExModel($this->getDoctrine());

        $list = $Model->getDonateList($start,$end);


        $this->data[$keyWord]["all"] = $list;

//        var_dump($list);

        $emptyUser = array(
            "nickName" => "虚位以待",
            "headPic" => BaseConfig::__USER_PIC_DEFAULT__,
            "money" => 0,
        );
        if (count($list) < 10) {
            for ( $i = count($list); $i < 10 ; $i++ ) {
                $list[$i] = $emptyUser;
            }
        }
        foreach ($list as $key => &$one) {
            $one["index"] = $key + 1;
            if (!$one["nickName"]) {
                $one["nickName"] = "萱氧会员_".$one["uid"];
//                $one["headPic"] = BaseConfig::__USER_PIC_DEFAULT__;
                $one["money"] = round($one["money"] ,2);
            }
            $one["money"] = round($one["money"] ,2);
            $this->log_out($one["money"]);
        }
        $this->data[$keyWord]["one"] = $list[0];
        $this->data[$keyWord]["two"] = $list[1];
        $this->data[$keyWord]["three"] = $list[2];
        $this->data[$keyWord]["list"] = array_slice($list,3);
    }



    /**
     * 自助开通VIP
     * @route("/share/join/vip",name="UserAppShareJoinVip")
     */
    public function UserAppShareJoinVip(Request $request)
    {
        $this->data["msg"] = "";

        //获取个人额度
        $UserDiyLevelupLimitModel = new UserDiyLevelupLimitModel($this->getDoctrine());
        $userLimit = $UserDiyLevelupLimitModel->getUser($this->needToBeUser());
        $this->data["limit"] = $userLimit;
        //获取已升级人员信息暂时不做
//        $UserDiyLevelUpModel = new UserDiyLevelUpModel($this->getDoctrine());
//        $upUser = $UserDiyLevelUpModel->getByUserId($this->needToBeUser());

        if ($request->getMethod() == "POST") {
            $list = [];
            $this->data["list"] = [];
            if($text = $this->getParamRequired("text")){
                $UserModel = new UserModel($this->getDoctrine());
                $user = $UserModel->getUserById($text);
                if (!$user) {
                    $user = $UserModel->getByPhone($text);
                }
                if ($user) {
                    $uid = $user->getId();
                    $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
                    $UserInvite = $UserInviteExModel->getUser($uid);
                    if ($UserInvite) {
                        $parent = $UserInvite->getParent();
                        $parentArray = $this->myExplodeNumbers($parent);
                        if (in_array($this->needToBeUser(),$parentArray)) {
                            $list[] = $user;
                        }
                        $this->data["list"] = $list;
                    }
                } else {
                    $this->data["msg"] = "用户未找到";
                }

            }

        } else {
            $this->data["list"] = [];
        }

        return $this->render("App/Wap/share_vip.php.twig",$this->data);
    }


    /**
     * @route("/share/reg",name="UserAppShareReg")
     */
    public function UserAppShareReg()
    {
        if(!$code = $this->getParamRequired("code")){
            //非正常扫码
        }

        $session = $this->mySession();

        $UserInviteExModel  = new UserInviteExModel($this->getDoctrine());
        $UserInvite = $UserInviteExModel->getUserByCode($code);
        if (!$UserInvite) {
            //非正常扫码
        }
        $UserModel = new UserModel($this->getDoctrine());
        $userFrom = $UserModel->getUserById($UserInvite->getUid());
        $fromOpenId = $userFrom->getOpenid();
        $session->set("fromOpenid",$fromOpenId);

        //设置好之后就可以开始获取用户的OpenId了
        $WechatModel = new WechatModel($this->getDoctrine());
        $url = BaseConfig::__BASE_URL__.$this->generateUrl("UserAppShareRegBind");

        $redirect = $WechatModel->getWeChatCode($url,1,$code);
        $this->log_out($redirect);
        die;
    }



    /**
     * @route("/share/bind",name="UserAppShareRegBind")
     */
    public function UserAppShareRegBind()
    {
        if(!$code = $this->getParamRequired("code")){
            //非正常扫码
        }
        if(!$userCode = $this->getParamRequired("state")){
            //非跳转进入
        }

        $session = $this->mySession();

        $UserInviteExModel  = new UserInviteExModel($this->getDoctrine());
        $UserInvite = $UserInviteExModel->getUserByCode($userCode);
        if (!$UserInvite) {
            //非正常扫码
        }

        $UserModel = new UserModel($this->getDoctrine());
        $userFrom = $UserModel->getUserById($UserInvite->getUid());
        $fromOpenId = $userFrom->getOpenid();
        $session->set("fromOpenid",$fromOpenId);

        //设置好之后就可以开始获取用户的OpenId了
        $WechatModel = new WechatModel($this->getDoctrine());

//        $WechatModel->getOpenidAndAccessToken($code);
        $WechatModel->getAccessToken4UserInfo($code);
        $myOpenid = $WechatModel->Openid;
        $userInfo = $WechatModel->getWeChatUserInfo();

        $curUser = $UserModel->getByWeChetId($myOpenid);
        $curUserInvite = $UserInviteExModel->getUser($curUser->getId());
        if (!$curUserInvite->getParent()) {
            $UserInviteExModel->addUser($curUser->getId(),$userCode);
        }
        $curUser->setNickName($userInfo->nickname)
            ->setHeadPic($userInfo->headimgurl)
            ->setOpenid($userInfo->openid)
        ;
        $this->myEm()->persist($curUser);
        $this->myEm()->flush();

        $sessData = $UserModel->createSessionData($curUser);
        $this->setSessionData($sessData);
        $phone = $curUser->getPhone();
        if (!$phone) {
            return $this->redirectToRoute("UserAppBindPhone");
        }else{
            return $this->redirectToRoute("UserAppHomeIndex");
        }


    }



    /**
     * @route("/share/material",name="UserAppShareMaterial")
     */
    public function UserAppShareMaterial()
    {
        $PlatConfigModel = new PlatConfigModel($this->getDoctrine());
        $PlatConfig = $PlatConfigModel->get(6);
        $this->data["qrCode"] = $PlatConfig->getPic();
        return $this->render("App/Wap/share_material.php.twig",$this->data);
    }

}
